package com.hywood.manager.live.service;

import com.hywood.util.Result;
import com.hywood.util.ResultUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin("*")
@RestController
public class FileUploadService {
    @Value("${upload.url}")
    private String URL;

    @RequestMapping(value = "/fileupload/", method = RequestMethod.POST)
    @ResponseBody
    public Result upload(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.error(-3, "文件内容为空");
        }
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filePath = "/var/www/html/upload/";
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffixName;
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return ResultUtil.success(URL + fileName);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-4, "上传失败");
    }
}
